package com.sinosoft.config;

import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.sinosoft.shiro.UserRealm;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;

@Configuration
public class ShiroConfig {

	/**
	 * 创建ShiroFilterFactoryBean
	 */
	@Bean
	public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager")DefaultWebSecurityManager securityManager) {
		ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
		//这只安全管理器
		shiroFilterFactoryBean.setSecurityManager(securityManager);
		/**
		 * Shiro内置过滤器，可以实现权限相关的拦截
		 * 		常用的过滤器：
		 * 			anon: 无需认证（登陆）可以直接访问
		 * 			authc： 必须认证才可以访问
		 * 			user: 如果使用rememberMe的功能可以直接访问
		 * 			perms: 该资源必须得到资源权限才可以访问
		 * 			role: 该资源必须得到角色权限才可以访问
		 */
		Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
		filterChainDefinitionMap.put("/shiro/testThymeleaf", "anon");
		filterChainDefinitionMap.put("/shiro/login", "anon");
		//授权验证
		filterChainDefinitionMap.put("/shiro/add", "perms[user:add]");
		filterChainDefinitionMap.put("/shiro/update", "perms[user:update]");
		filterChainDefinitionMap.put("/shiro/*", "authc");
		//登陆页面
		shiroFilterFactoryBean.setLoginUrl("/shiro/tologin");
		//未授权页面
		shiroFilterFactoryBean.setUnauthorizedUrl("/shiro/unAuth");
		shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
		return shiroFilterFactoryBean;
	}
	
	/**
	 * 创建DefaultWebSecurityManager
	 */
	@Bean(name="securityManager")
	public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm")UserRealm uerRealm) {
		DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
		securityManager.setRealm(uerRealm);
		return securityManager;
	}
	
	
	/**
	 * 创建Realm
	 */
	@Bean(name="userRealm")
	public UserRealm getRealm() {
		return new UserRealm();
	}
	
	/**
	 * 创建ShiroDialect
	 */
	@Bean
	public ShiroDialect getShiroDialect() {
		return new ShiroDialect();
	}
	
}
